/**
 * 分析结果页面全面测试脚本
 * 测试所有功能模块，包括分页控件、详情界面、响应式设计等
 */

class AnalysisResultsTestSuite {
    constructor() {
        this.testResults = [];
        this.currentTest = 0;
        this.totalTests = 0;
        this.baseUrl = 'http://localhost:8000';
        this.testStartTime = null;
        this.testEndTime = null;

        // 测试配置
        this.testConfig = {
            // 分页测试配置
            pagination: {
                testSizes: [5, 10, 15, 20, 30, 50, 100],
                navigationPages: [1, 2, 3, 5, 10],
                maxWaitTime: 5000
            },

            // 详情界面测试配置
            details: {
                analysisTypes: ['regional', 'complaint-type', 'sentiment', 'compliance', 'duplicate'],
                modalTests: ['open', 'close', 'keyboard', 'outside_click'],
                visualizations: ['map', 'chart', 'keyword_cloud']
            },

            // 响应式测试配置
            responsive: {
                viewports: [
                    { name: 'Mobile', width: 375, height: 667 },
                    { name: 'Tablet', width: 768, height: 1024 },
                    { name: 'Desktop', width: 1920, height: 1080 }
                ]
            },

            // 性能测试配置
            performance: {
                maxLoadTime: 3000,
                maxResponseTime: 1000,
                maxMemoryUsage: 50 // MB
            }
        };

        // 测试数据
        this.testData = {
            petitionRecords: [],
            analysisResults: {
                regional: [],
                complaintType: [],
                sentiment: [],
                compliance: [],
                duplicate: []
            }
        };

        this.init();
    }

    /**
     * 初始化测试套件
     */
    init() {
        console.log('🧪 分析结果页面测试套件初始化...');
        this.setupTestEnvironment();
        this.registerTestListeners();
    }

    /**
     * 设置测试环境
     */
    setupTestEnvironment() {
        // 创建测试报告容器
        const testContainer = document.createElement('div');
        testContainer.id = 'test-suite-container';
        testContainer.className = 'fixed inset-0 bg-black bg-opacity-90 z-50 overflow-y-auto';
        testContainer.innerHTML = `
            <div class="min-h-screen p-6">
                <div class="max-w-6xl mx-auto">
                    <div class="bg-white rounded-xl shadow-2xl p-6">
                        <div class="flex items-center justify-between mb-6">
                            <h1 class="text-2xl font-bold text-slate-800">
                                <i class="fas fa-flask mr-2"></i>分析结果页面测试套件
                            </h1>
                            <button id="closeTestSuite" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                                <i class="fas fa-times mr-2"></i>关闭
                            </button>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                            <div class="bg-blue-50 rounded-lg p-4">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm font-medium text-blue-600">总测试数</span>
                                    <span id="totalTests" class="text-2xl font-bold text-blue-800">0</span>
                                </div>
                            </div>
                            <div class="bg-green-50 rounded-lg p-4">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm font-medium text-green-600">通过</span>
                                    <span id="passedTests" class="text-2xl font-bold text-green-800">0</span>
                                </div>
                            </div>
                            <div class="bg-red-50 rounded-lg p-4">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm font-medium text-red-600">失败</span>
                                    <span id="failedTests" class="text-2xl font-bold text-red-800">0</span>
                                </div>
                            </div>
                            <div class="bg-yellow-50 rounded-lg p-4">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm font-medium text-yellow-600">进度</span>
                                    <span id="testProgress" class="text-2xl font-bold text-yellow-800">0%</span>
                                </div>
                            </div>
                        </div>

                        <div class="mb-6">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-medium text-slate-600">测试进度</span>
                                <span id="currentTestName" class="text-sm text-slate-500">准备开始...</span>
                            </div>
                            <div class="w-full bg-slate-200 rounded-full h-2">
                                <div id="progressBar" class="bg-blue-600 h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
                            </div>
                        </div>

                        <div class="space-y-4">
                            <div class="flex space-x-4">
                                <button id="runAllTests" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                                    <i class="fas fa-play mr-2"></i>运行所有测试
                                </button>
                                <button id="runPaginationTests" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                                    <i class="fas fa-list mr-2"></i>分页测试
                                </button>
                                <button id="runDetailTests" class="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
                                    <i class="fas fa-eye mr-2"></i>详情测试
                                </button>
                                <button id="runResponsiveTests" class="px-6 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">
                                    <i class="fas fa-mobile-alt mr-2"></i>响应式测试
                                </button>
                            </div>
                        </div>

                        <div id="testResults" class="mt-6 space-y-4">
                            <div class="text-center text-slate-500 py-8">
                                <i class="fas fa-flask text-4xl mb-4"></i>
                                <p>点击上方按钮开始测试</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(testContainer);

        // 绑定事件
        document.getElementById('closeTestSuite').addEventListener('click', () => {
            document.getElementById('test-suite-container').remove();
        });

        document.getElementById('runAllTests').addEventListener('click', () => {
            this.runAllTests();
        });

        document.getElementById('runPaginationTests').addEventListener('click', () => {
            this.runPaginationTests();
        });

        document.getElementById('runDetailTests').addEventListener('click', () => {
            this.runDetailTests();
        });

        document.getElementById('runResponsiveTests').addEventListener('click', () => {
            this.runResponsiveTests();
        });
    }

    /**
     * 注册测试监听器
     */
    registerTestListeners() {
        // 监听页面变化
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'childList') {
                    this.checkPageElements();
                }
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    /**
     * 运行所有测试
     */
    async runAllTests() {
        console.log('🚀 开始运行所有测试...');
        this.testStartTime = Date.now();
        this.resetTestResults();

        const testGroups = [
            { name: '页面基础功能', tests: () => this.testBasicFunctionality() },
            { name: '分页控件功能', tests: () => this.testPaginationFunctionality() },
            { name: '详情界面功能', tests: () => this.testDetailFunctionality() },
            { name: '响应式设计', tests: () => this.testResponsiveDesign() },
            { name: '用户体验', tests: () => this.testUserExperience() },
            { name: '性能测试', tests: () => this.testPerformance() }
        ];

        for (const group of testGroups) {
            console.log(`📋 运行测试组: ${group.name}`);
            await this.runTestGroup(group.name, group.tests);
            await this.delay(1000); // 组间延迟
        }

        this.generateTestReport();
    }

    /**
     * 运行分页测试
     */
    async runPaginationTests() {
        console.log('📄 运行分页控件测试...');
        this.resetTestResults();
        await this.runTestGroup('分页控件功能', () => this.testPaginationFunctionality());
        this.generateTestReport();
    }

    /**
     * 运行详情测试
     */
    async runDetailTests() {
        console.log('👁️ 运行详情界面测试...');
        this.resetTestResults();
        await this.runTestGroup('详情界面功能', () => this.testDetailFunctionality());
        this.generateTestReport();
    }

    /**
     * 运行响应式测试
     */
    async runResponsiveTests() {
        console.log('📱 运行响应式设计测试...');
        this.resetTestResults();
        await this.runTestGroup('响应式设计', () => this.testResponsiveDesign());
        this.generateTestReport();
    }

    /**
     * 运行测试组
     */
    async runTestGroup(groupName, testFunction) {
        const resultsContainer = document.getElementById('testResults');
        const groupElement = document.createElement('div');
        groupElement.className = 'border border-slate-200 rounded-lg p-4';
        groupElement.innerHTML = `
            <h3 class="text-lg font-semibold text-slate-800 mb-3">
                <i class="fas fa-cogs mr-2"></i>${groupName}
            </h3>
            <div class="space-y-2" id="${groupName.replace(/\s+/g, '-')}-results">
                <div class="text-slate-500 text-center py-4">测试运行中...</div>
            </div>
        `;
        resultsContainer.appendChild(groupElement);

        try {
            await testFunction();
        } catch (error) {
            console.error(`测试组 ${groupName} 执行失败:`, error);
            this.addTestResult({
                name: `${groupName} 执行失败`,
                status: 'failed',
                error: error.message,
                details: error.stack
            });
        }
    }

    /**
     * 测试页面基础功能
     */
    async testBasicFunctionality() {
        console.log('🔍 测试页面基础功能...');

        // 测试1: 检查页面元素是否存在
        this.addTestResult({
            name: '页面基础元素检查',
            status: 'running'
        });

        const requiredElements = [
            'analysis-tab',
            'taskFilter',
            'resultsTableContainer',
            'resultDetailModal',
            'pageSizeSelect'
        ];

        let missingElements = [];
        requiredElements.forEach(elementId => {
            const element = document.getElementById(elementId) || document.querySelector(`.${elementId}`);
            if (!element) {
                missingElements.push(elementId);
            }
        });

        if (missingElements.length === 0) {
            this.addTestResult({
                name: '页面基础元素检查',
                status: 'passed',
                details: '所有必需的页面元素都存在'
            });
        } else {
            this.addTestResult({
                name: '页面基础元素检查',
                status: 'failed',
                error: `缺少元素: ${missingElements.join(', ')}`
            });
        }

        await this.delay(500);

        // 测试2: 检查Tab切换功能
        this.addTestResult({
            name: 'Tab切换功能',
            status: 'running'
        });

        const tabs = document.querySelectorAll('.analysis-tab');
        if (tabs.length === 5) {
            // 模拟点击每个Tab
            for (let i = 0; i < tabs.length; i++) {
                tabs[i].click();
                await this.delay(300);
            }

            this.addTestResult({
                name: 'Tab切换功能',
                status: 'passed',
                details: `成功测试了 ${tabs.length} 个Tab的切换功能`
            });
        } else {
            this.addTestResult({
                name: 'Tab切换功能',
                status: 'failed',
                error: `期望5个Tab，实际找到${tabs.length}个`
            });
        }

        await this.delay(500);

        // 测试3: 检查分析结果管理器是否初始化
        this.addTestResult({
            name: '分析结果管理器初始化',
            status: 'running'
        });

        if (window.analysisResultsManager) {
            this.addTestResult({
                name: '分析结果管理器初始化',
                status: 'passed',
                details: '分析结果管理器已正确初始化'
            });
        } else {
            this.addTestResult({
                name: '分析结果管理器初始化',
                status: 'failed',
                error: '分析结果管理器未初始化'
            });
        }
    }

    /**
     * 测试分页控件功能
     */
    async testPaginationFunctionality() {
        console.log('📄 测试分页控件功能...');

        // 测试1: 检查分页控件元素
        this.addTestResult({
            name: '分页控件元素检查',
            status: 'running'
        });

        const paginationElements = {
            pageSizeSelect: document.getElementById('pageSizeSelect'),
            paginationContainer: document.getElementById('paginationContainer'),
            pageStart: document.getElementById('pageStart'),
            pageEnd: document.getElementById('pageEnd'),
            totalItems: document.getElementById('totalItems')
        };

        let missingElements = [];
        Object.keys(paginationElements).forEach(key => {
            if (!paginationElements[key]) {
                missingElements.push(key);
            }
        });

        if (missingElements.length === 0) {
            this.addTestResult({
                name: '分页控件元素检查',
                status: 'passed',
                details: '所有分页控件元素都存在'
            });
        } else {
            this.addTestResult({
                name: '分页控件元素检查',
                status: 'failed',
                error: `缺少分页元素: ${missingElements.join(', ')}`
            });
        }

        await this.delay(500);

        // 测试2: 页面大小选择器功能
        this.addTestResult({
            name: '页面大小选择器功能',
            status: 'running'
        });

        const pageSizeSelect = document.getElementById('pageSizeSelect');
        if (pageSizeSelect) {
            const options = Array.from(pageSizeSelect.options);
            const expectedSizes = [5, 10, 15, 20, 30, 50, 100];
            const actualSizes = options.map(option => parseInt(option.value));

            if (JSON.stringify(expectedSizes.sort()) === JSON.stringify(actualSizes.sort())) {
                // 测试切换页面大小
                const originalValue = pageSizeSelect.value;
                pageSizeSelect.value = '20';
                pageSizeSelect.dispatchEvent(new Event('change'));
                await this.delay(300);

                this.addTestResult({
                    name: '页面大小选择器功能',
                    status: 'passed',
                    details: `页面大小选择器包含${expectedSizes.length}个选项，切换功能正常`
                });
            } else {
                this.addTestResult({
                    name: '页面大小选择器功能',
                    status: 'failed',
                    error: `期望选项: ${expectedSizes.join(',')}，实际: ${actualSizes.join(',')}`
                });
            }
        } else {
            this.addTestResult({
                name: '页面大小选择器功能',
                status: 'failed',
                error: '页面大小选择器不存在'
            });
        }

        await this.delay(500);

        // 测试3: 分页按钮布局
        this.addTestResult({
            name: '分页按钮布局',
            status: 'running'
        });

        const paginationContainer = document.getElementById('paginationContainer');
        if (paginationContainer) {
            // 模拟创建分页按钮来测试布局
            const mockPaginationHTML = this.createMockPaginationHTML(10, 3);
            paginationContainer.innerHTML = mockPaginationHTML;

            await this.delay(200);

            const buttons = paginationContainer.querySelectorAll('.pagination-btn');
            const containerRect = paginationContainer.getBoundingClientRect();

            // 检查按钮是否溢出
            const buttonsWidth = Array.from(buttons).reduce((total, btn) => {
                return total + btn.getBoundingClientRect().width;
            }, 0);

            if (buttonsWidth <= containerRect.width) {
                this.addTestResult({
                    name: '分页按钮布局',
                    status: 'passed',
                    details: `分页按钮布局正常，总宽度${Math.round(buttonsWidth)}px，容器宽度${Math.round(containerRect.width)}px`
                });
            } else {
                this.addTestResult({
                    name: '分页按钮布局',
                    status: 'failed',
                    error: `分页按钮宽度${Math.round(buttonsWidth)}px超出容器宽度${Math.round(containerRect.width)}px`
                });
            }
        } else {
            this.addTestResult({
                name: '分页按钮布局',
                status: 'failed',
                error: '分页容器不存在'
            });
        }

        await this.delay(500);

        // 测试4: 响应式分页
        this.addTestResult({
            name: '响应式分页',
            status: 'running'
        });

        // 测试不同屏幕尺寸下的分页显示
        const viewports = [
            { width: 375, name: 'Mobile' },
            { width: 768, name: 'Tablet' },
            { width: 1920, name: 'Desktop' }
        ];

        let responsiveTests = [];

        for (const viewport of viewports) {
            // 临时修改视口宽度
            const originalWidth = window.innerWidth;
            Object.defineProperty(window, 'innerWidth', {
                writable: true,
                configurable: true,
                value: viewport.width
            });

            // 触发窗口大小改变事件
            window.dispatchEvent(new Event('resize'));
            await this.delay(200);

            // 检查分页按钮数量
            const paginationButtons = document.querySelectorAll('.pagination-btn');
            const visibleButtons = Array.from(paginationButtons).filter(btn => {
                const rect = btn.getBoundingClientRect();
                return rect.width > 0 && rect.height > 0;
            });

            responsiveTests.push({
                viewport: viewport.name,
                width: viewport.width,
                buttonCount: visibleButtons.length
            });

            // 恢复原始宽度
            Object.defineProperty(window, 'innerWidth', {
                writable: true,
                configurable: true,
                value: originalWidth
            });
        }

        // 恢复窗口大小
        window.dispatchEvent(new Event('resize'));

        this.addTestResult({
            name: '响应式分页',
            status: 'passed',
            details: `响应式测试完成: ${responsiveTests.map(t => `${t.viewport}(${t.buttonCount}按钮)`).join(', ')}`
        });
    }

    /**
     * 测试详情界面功能
     */
    async testDetailFunctionality() {
        console.log('👁️ 测试详情界面功能...');

        // 测试1: 模态框基础功能
        this.addTestResult({
            name: '模态框基础功能',
            status: 'running'
        });

        const modal = document.getElementById('resultDetailModal');
        const modalContent = document.getElementById('resultDetailContent');

        if (modal && modalContent) {
            // 测试打开模态框
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            await this.delay(300);

            const isVisible = !modal.classList.contains('hidden') && modal.classList.contains('flex');

            // 测试关闭模态框
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            await this.delay(200);

            const isHidden = modal.classList.contains('hidden') && !modal.classList.contains('flex');

            if (isVisible && isHidden) {
                this.addTestResult({
                    name: '模态框基础功能',
                    status: 'passed',
                    details: '模态框打开/关闭功能正常'
                });
            } else {
                this.addTestResult({
                    name: '模态框基础功能',
                    status: 'failed',
                    error: `打开: ${isVisible}, 关闭: ${isHidden}`
                });
            }
        } else {
            this.addTestResult({
                name: '模态框基础功能',
                status: 'failed',
                error: modal ? '模态框内容不存在' : '模态框不存在'
            });
        }

        await this.delay(500);

        // 测试2: 详情渲染功能
        this.addTestResult({
            name: '详情渲染功能',
            status: 'running'
        });

        if (window.analysisResultsManager) {
            const testData = {
                petition_record_id: 'TEST001',
                created_at: new Date().toISOString(),
                confidence_score: 0.85
            };

            try {
                // 测试区域分析详情渲染
                window.analysisResultsManager.renderRegionalDetail(testData);
                await this.delay(300);

                const content = document.getElementById('resultDetailContent');
                const hasContent = content && content.innerHTML.length > 100;

                if (hasContent) {
                    this.addTestResult({
                        name: '详情渲染功能',
                        status: 'passed',
                        details: '详情内容渲染正常'
                    });
                } else {
                    this.addTestResult({
                        name: '详情渲染功能',
                        status: 'failed',
                        error: '详情内容渲染失败'
                    });
                }
            } catch (error) {
                this.addTestResult({
                    name: '详情渲染功能',
                    status: 'failed',
                    error: error.message
                });
            }
        } else {
            this.addTestResult({
                name: '详情渲染功能',
                status: 'failed',
                error: '分析结果管理器不存在'
            });
        }

        await this.delay(500);

        // 测试3: 五种分析类型详情
        this.addTestResult({
            name: '五种分析类型详情',
            status: 'running'
        });

        const analysisTypes = ['regional', 'complaint-type', 'sentiment', 'compliance', 'duplicate'];
        const testMethods = {
            'regional': 'renderRegionalDetail',
            'complaint-type': 'renderComplaintTypeDetail',
            'sentiment': 'renderSentimentDetail',
            'compliance': 'renderComplianceDetail',
            'duplicate': 'renderDuplicateDetail'
        };

        let successfulTypes = [];

        if (window.analysisResultsManager) {
            for (const type of analysisTypes) {
                try {
                    const testData = this.createMockData(type);
                    window.analysisResultsManager[testMethods[type]](testData);
                    await this.delay(200);

                    const content = document.getElementById('resultDetailContent');
                    if (content && content.innerHTML.includes(type === 'complaint-type' ? '投诉类型' : type)) {
                        successfulTypes.push(type);
                    }
                } catch (error) {
                    console.error(`测试 ${type} 详情失败:`, error);
                }
            }
        }

        if (successfulTypes.length === analysisTypes.length) {
            this.addTestResult({
                name: '五种分析类型详情',
                status: 'passed',
                details: `成功测试了所有${analysisTypes.length}种分析类型的详情渲染`
            });
        } else {
            this.addTestResult({
                name: '五种分析类型详情',
                status: 'failed',
                error: `成功类型: ${successfulTypes.join(', ')}，失败: ${analysisTypes.filter(t => !successfulTypes.includes(t)).join(', ')}`
            });
        }

        await this.delay(500);

        // 测试4: 可视化组件
        this.addTestResult({
            name: '可视化组件',
            status: 'running'
        });

        let visualizationTests = [];

        // 测试图表组件
        if (typeof Chart !== 'undefined') {
            visualizationTests.push('Chart.js');
        } else {
            console.warn('Chart.js未加载');
        }

        // 测试地图组件
        if (typeof L !== 'undefined') {
            visualizationTests.push('Leaflet');
        } else {
            console.warn('Leaflet未加载');
        }

        this.addTestResult({
            name: '可视化组件',
            status: visualizationTests.length > 0 ? 'passed' : 'failed',
            details: visualizationTests.length > 0 ? `可用组件: ${visualizationTests.join(', ')}` : '没有可用的可视化组件'
        });
    }

    /**
     * 测试响应式设计
     */
    async testResponsiveDesign() {
        console.log('📱 测试响应式设计...');

        const viewports = this.testConfig.responsive.viewports;

        for (const viewport of viewports) {
            this.addTestResult({
                name: `${viewport.name} 响应式布局`,
                status: 'running'
            });

            // 保存原始尺寸
            const originalWidth = window.innerWidth;
            const originalHeight = window.innerHeight;

            try {
                // 模拟视口尺寸
                Object.defineProperty(window, 'innerWidth', {
                    writable: true,
                    configurable: true,
                    value: viewport.width
                });

                Object.defineProperty(window, 'innerHeight', {
                    writable: true,
                    configurable: true,
                    value: viewport.height
                });

                // 触发resize事件
                window.dispatchEvent(new Event('resize'));
                await this.delay(300);

                // 检查布局适应性
                const layoutTests = this.checkLayoutAdaptability(viewport);

                if (layoutTests.passed) {
                    this.addTestResult({
                        name: `${viewport.name} 响应式布局`,
                        status: 'passed',
                        details: layoutTests.details
                    });
                } else {
                    this.addTestResult({
                        name: `${viewport.name} 响应式布局`,
                        status: 'failed',
                        error: layoutTests.error
                    });
                }

            } catch (error) {
                this.addTestResult({
                    name: `${viewport.name} 响应式布局`,
                    status: 'failed',
                    error: error.message
                });
            } finally {
                // 恢复原始尺寸
                Object.defineProperty(window, 'innerWidth', {
                    writable: true,
                    configurable: true,
                    value: originalWidth
                });

                Object.defineProperty(window, 'innerHeight', {
                    writable: true,
                    configurable: true,
                    value: originalHeight
                });

                window.dispatchEvent(new Event('resize'));
                await this.delay(200);
            }
        }

        await this.delay(500);

        // 测试触控支持
        this.addTestResult({
            name: '触控支持',
            status: 'running'
        });

        const touchTests = this.testTouchSupport();

        if (touchTests.passed) {
            this.addTestResult({
                name: '触控支持',
                status: 'passed',
                details: touchTests.details
            });
        } else {
            this.addTestResult({
                name: '触控支持',
                status: 'failed',
                error: touchTests.error
            });
        }
    }

    /**
     * 测试用户体验
     */
    async testUserExperience() {
        console.log('👤 测试用户体验...');

        // 测试1: 加载状态
        this.addTestResult({
            name: '加载状态',
            status: 'running'
        });

        if (window.analysisResultsManager) {
            // 测试加载状态显示
            window.analysisResultsManager.showLoading(true);
            await this.delay(200);

            const loadingElement = document.getElementById('resultsLoadingState');
            const isLoadingVisible = loadingElement && !loadingElement.classList.contains('hidden');

            window.analysisResultsManager.showLoading(false);
            await this.delay(200);

            const isLoadingHidden = loadingElement && loadingElement.classList.contains('hidden');

            if (isLoadingVisible && isLoadingHidden) {
                this.addTestResult({
                    name: '加载状态',
                    status: 'passed',
                    details: '加载状态显示/隐藏功能正常'
                });
            } else {
                this.addTestResult({
                    name: '加载状态',
                    status: 'failed',
                    error: `显示: ${isLoadingVisible}, 隐藏: ${isLoadingHidden}`
                });
            }
        } else {
            this.addTestResult({
                name: '加载状态',
                status: 'failed',
                error: '分析结果管理器不存在'
            });
        }

        await this.delay(500);

        // 测试2: 错误处理
        this.addTestResult({
            name: '错误处理',
            status: 'running'
        });

        if (window.analysisResultsManager) {
            // 清除现有错误提示
            const existingError = document.querySelector('.analysis-error-toast');
            if (existingError) {
                existingError.remove();
            }

            // 测试错误显示
            window.analysisResultsManager.showError('测试错误消息');
            await this.delay(300);

            const errorElement = document.querySelector('.analysis-error-toast');
            const isErrorVisible = errorElement && errorElement.getBoundingClientRect().width > 0;

            // 清除错误提示
            if (errorElement) {
                errorElement.remove();
            }

            if (isErrorVisible) {
                this.addTestResult({
                    name: '错误处理',
                    status: 'passed',
                    details: '错误提示显示功能正常'
                });
            } else {
                this.addTestResult({
                    name: '错误处理',
                    status: 'failed',
                    error: '错误提示显示失败'
                });
            }
        } else {
            this.addTestResult({
                name: '错误处理',
                status: 'failed',
                error: '分析结果管理器不存在'
            });
        }

        await this.delay(500);

        // 测试3: 键盘导航
        this.addTestResult({
            name: '键盘导航',
            status: 'running'
        });

        const keyboardTests = this.testKeyboardNavigation();

        if (keyboardTests.passed) {
            this.addTestResult({
                name: '键盘导航',
                status: 'passed',
                details: keyboardTests.details
            });
        } else {
            this.addTestResult({
                name: '键盘导航',
                status: 'failed',
                error: keyboardTests.error
            });
        }
    }

    /**
     * 测试性能
     */
    async testPerformance() {
        console.log('⚡ 测试性能...');

        // 测试1: 页面加载时间
        this.addTestResult({
            name: '页面加载时间',
            status: 'running'
        });

        const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart;
        const maxLoadTime = this.testConfig.performance.maxLoadTime;

        if (loadTime < maxLoadTime) {
            this.addTestResult({
                name: '页面加载时间',
                status: 'passed',
                details: `页面加载时间: ${loadTime}ms (限制: ${maxLoadTime}ms)`
            });
        } else {
            this.addTestResult({
                name: '页面加载时间',
                status: 'failed',
                error: `页面加载时间 ${loadTime}ms 超过限制 ${maxLoadTime}ms`
            });
        }

        await this.delay(500);

        // 测试2: 内存使用
        this.addTestResult({
            name: '内存使用',
            status: 'running'
        });

        if (performance.memory) {
            const memoryUsage = performance.memory.usedJSHeapSize / (1024 * 1024); // MB
            const maxMemoryUsage = this.testConfig.performance.maxMemoryUsage;

            if (memoryUsage < maxMemoryUsage) {
                this.addTestResult({
                    name: '内存使用',
                    status: 'passed',
                    details: `内存使用: ${memoryUsage.toFixed(2)}MB (限制: ${maxMemoryUsage}MB)`
                });
            } else {
                this.addTestResult({
                    name: '内存使用',
                    status: 'failed',
                    error: `内存使用 ${memoryUsage.toFixed(2)}MB 超过限制 ${maxMemoryUsage}MB`
                });
            }
        } else {
            this.addTestResult({
                name: '内存使用',
                status: 'skipped',
                details: '浏览器不支持内存API'
            });
        }
    }

    /**
     * 创建模拟分页HTML
     */
    createMockPaginationHTML(totalPages, currentPage) {
        let html = '';

        // 上一页
        html += `<button class="page-btn pagination-btn px-3 py-2 rounded-lg ${currentPage === 1 ? 'disabled' : ''}" data-page="${currentPage - 1}" ${currentPage === 1 ? 'disabled' : ''}><i class="fas fa-chevron-left"></i></button>`;

        // 页码按钮
        const maxVisiblePages = 5;
        const startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        const endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        for (let i = startPage; i <= endPage; i++) {
            html += `<button class="page-btn pagination-btn px-3 py-2 rounded-lg ${i === currentPage ? 'active' : ''}" data-page="${i}">${i}</button>`;
        }

        // 下一页
        html += `<button class="page-btn pagination-btn px-3 py-2 rounded-lg ${currentPage === totalPages ? 'disabled' : ''}" data-page="${currentPage + 1}" ${currentPage === totalPages ? 'disabled' : ''}><i class="fas fa-chevron-right"></i></button>`;

        return html;
    }

    /**
     * 创建模拟数据
     */
    createMockData(type) {
        const baseData = {
            petition_record_id: 'TEST001',
            created_at: new Date().toISOString(),
            xfnr: '这是一个测试信访内容，用于验证详情界面的渲染功能。',
            dzxx_tsdx: '测试单位',
            dzxx_tsdz: '测试地址',
            dzxx_xzq: '测试区',
            dzxx_jd: '测试街道'
        };

        switch (type) {
            case 'regional':
                return {
                    ...baseData,
                    tsr: '测试人',
                    confidence_score: 0.85,
                    has_location: true,
                    location_coordinates: [116.404, 39.915],
                    dzxx_dx_words: '关键词1,关键词2',
                    dzxx_dz_words: '地址关键词1,地址关键词2'
                };
            case 'complaint-type':
                return {
                    ...baseData,
                    tslx_yj: '一级分类',
                    tslx_rj: '二级分类',
                    tslx_sj: '三级分类',
                    tslx_yjyj: '一级分类依据',
                    tslx_rjyj: '二级分类依据',
                    tslx_sjyj: '三级分类依据',
                    level2_confidence: 0.8,
                    level3_confidence: 0.75
                };
            case 'sentiment':
                return {
                    ...baseData,
                    sentiment_level: '负面',
                    qgfx_zy: '这是一个情感摘要。',
                    qgfx_pdly: '情感判断理由。',
                    keywords_list: ['关键词1', '关键词2', '关键词3']
                };
            case 'compliance':
                return {
                    ...baseData,
                    gffx_dfnr: '这是答复内容。',
                    compliance_status: '合规',
                    is_compliant: true,
                    gffx_pdly: '合规判断理由。',
                    ts_qxdw: '去向单位'
                };
            case 'duplicate':
                return {
                    cfbh: 'CF001',
                    xfxh: 'XF001',
                    task_id: 'TASK001'
                };
            default:
                return baseData;
        }
    }

    /**
     * 检查布局适应性
     */
    checkLayoutAdaptability(viewport) {
        const checks = [];

        // 检查主要容器
        const mainContainer = document.querySelector('.space-y-6');
        if (mainContainer) {
            const containerWidth = mainContainer.getBoundingClientRect().width;
            checks.push(`主容器宽度: ${containerWidth}px`);

            // 检查是否出现水平滚动条
            const hasHorizontalScroll = document.documentElement.scrollWidth > document.documentElement.clientWidth;
            if (hasHorizontalScroll) {
                return {
                    passed: false,
                    error: `${viewport.name} 出现水平滚动条`
                };
            }
        }

        // 检查表格响应式
        const tableContainer = document.querySelector('.overflow-x-auto');
        if (tableContainer) {
            const table = tableContainer.querySelector('table');
            if (table) {
                const tableWidth = table.getBoundingClientRect().width;
                const containerWidth = tableContainer.getBoundingClientRect().width;

                if (tableWidth > containerWidth) {
                    checks.push(`表格宽度(${tableWidth}px) > 容器宽度(${containerWidth}px)，需要横向滚动`);
                } else {
                    checks.push(`表格适配容器宽度`);
                }
            }
        }

        // 检查分页控件
        const paginationContainer = document.getElementById('resultsPagination');
        if (paginationContainer) {
            const paginationRect = paginationContainer.getBoundingClientRect();
            const paginationButtons = paginationContainer.querySelectorAll('.pagination-btn');

            if (paginationButtons.length > 0) {
                const buttonsFit = Array.from(paginationButtons).every(btn => {
                    const rect = btn.getBoundingClientRect();
                    return rect.top >= paginationRect.top && rect.bottom <= paginationRect.bottom;
                });

                if (buttonsFit) {
                    checks.push('分页按钮布局正常');
                } else {
                    return {
                        passed: false,
                        error: `${viewport.name} 分页按钮布局异常`
                    };
                }
            }
        }

        return {
            passed: true,
            details: checks.join(', ')
        };
    }

    /**
     * 测试触控支持
     */
    testTouchSupport() {
        const checks = [];

        // 检查是否支持触控事件
        const hasTouchSupport = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        checks.push(`触控支持: ${hasTouchSupport ? '是' : '否'}`);

        // 检查按钮大小
        const buttons = document.querySelectorAll('button');
        const minButtonSize = 44; // 最小触控目标尺寸

        const smallButtons = Array.from(buttons).filter(btn => {
            const rect = btn.getBoundingClientRect();
            return rect.width < minButtonSize || rect.height < minButtonSize;
        });

        if (smallButtons.length === 0) {
            checks.push('所有按钮都满足最小触控尺寸');
        } else {
            return {
                passed: false,
                error: `${smallButtons.length}个按钮尺寸小于最小触控要求`
            };
        }

        return {
            passed: true,
            details: checks.join(', ')
        };
    }

    /**
     * 测试键盘导航
     */
    testKeyboardNavigation() {
        const checks = [];

        // 检查可聚焦元素
        const focusableElements = document.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
        checks.push(`可聚焦元素: ${focusableElements.length}个`);

        // 检查Tab键顺序
        const firstElement = focusableElements[0];
        const lastElement = focusableElements[focusableElements.length - 1];

        if (firstElement && lastElement) {
            // 模拟Tab键导航
            firstElement.focus();
            const hasFocus = document.activeElement === firstElement;
            checks.push(`Tab导航: ${hasFocus ? '正常' : '异常'}`);
        }

        // 检查键盘快捷键
        const hasKeyboardShortcuts = document.querySelector('[data-keyboard-shortcut]') !== null;
        checks.push(`键盘快捷键: ${hasKeyboardShortcuts ? '有' : '无'}`);

        return {
            passed: true,
            details: checks.join(', ')
        };
    }

    /**
     * 添加测试结果
     */
    addTestResult(result) {
        const testResult = {
            name: result.name,
            status: result.status,
            timestamp: new Date().toISOString(),
            details: result.details || '',
            error: result.error || '',
            duration: result.duration || 0
        };

        this.testResults.push(testResult);
        this.updateTestDisplay(testResult);
        this.updateProgress();
    }

    /**
     * 更新测试显示
     */
    updateTestDisplay(testResult) {
        const resultsContainer = document.getElementById('testResults');

        // 查找对应的测试组容器
        let groupContainer = null;
        for (const group of ['页面基础功能', '分页控件功能', '详情界面功能', '响应式设计', '用户体验', '性能测试']) {
            const container = document.getElementById(`${group.replace(/\s+/g, '-')}-results`);
            if (container) {
                groupContainer = container;
                break;
            }
        }

        if (!groupContainer) {
            groupContainer = resultsContainer;
        }

        // 创建测试结果元素
        const resultElement = document.createElement('div');
        resultElement.className = `flex items-center justify-between p-3 rounded-lg ${this.getStatusClass(testResult.status)}`;

        const statusIcon = this.getStatusIcon(testResult.status);

        resultElement.innerHTML = `
            <div class="flex items-center space-x-3">
                <i class="${statusIcon}"></i>
                <span class="font-medium">${testResult.name}</span>
            </div>
            <div class="flex items-center space-x-2">
                ${testResult.details ? `<span class="text-sm text-slate-600">${testResult.details}</span>` : ''}
                ${testResult.error ? `<span class="text-sm text-red-600">${testResult.error}</span>` : ''}
                <span class="text-sm text-slate-500">${new Date(testResult.timestamp).toLocaleTimeString()}</span>
            </div>
        `;

        // 如果是第一个测试结果，清除占位符
        const placeholder = groupContainer.querySelector('.text-slate-500');
        if (placeholder) {
            placeholder.remove();
        }

        groupContainer.appendChild(resultElement);

        // 更新统计数据
        this.updateTestStats();
    }

    /**
     * 获取状态样式类
     */
    getStatusClass(status) {
        switch (status) {
            case 'passed':
                return 'bg-green-50 text-green-800';
            case 'failed':
                return 'bg-red-50 text-red-800';
            case 'running':
                return 'bg-blue-50 text-blue-800';
            case 'skipped':
                return 'bg-yellow-50 text-yellow-800';
            default:
                return 'bg-slate-50 text-slate-800';
        }
    }

    /**
     * 获取状态图标
     */
    getStatusIcon(status) {
        switch (status) {
            case 'passed':
                return 'fas fa-check-circle text-green-600';
            case 'failed':
                return 'fas fa-times-circle text-red-600';
            case 'running':
                return 'fas fa-spinner fa-spin text-blue-600';
            case 'skipped':
                return 'fas fa-minus-circle text-yellow-600';
            default:
                return 'fas fa-question-circle text-slate-600';
        }
    }

    /**
     * 更新测试统计
     */
    updateTestStats() {
        const totalTests = this.testResults.length;
        const passedTests = this.testResults.filter(r => r.status === 'passed').length;
        const failedTests = this.testResults.filter(r => r.status === 'failed').length;
        const runningTests = this.testResults.filter(r => r.status === 'running').length;

        document.getElementById('totalTests').textContent = totalTests;
        document.getElementById('passedTests').textContent = passedTests;
        document.getElementById('failedTests').textContent = failedTests;

        // 更新进度
        const progress = totalTests > 0 ? ((passedTests + failedTests) / totalTests) * 100 : 0;
        document.getElementById('testProgress').textContent = `${Math.round(progress)}%`;
        document.getElementById('progressBar').style.width = `${progress}%`;

        // 更新当前测试名称
        const currentTest = this.testResults.find(r => r.status === 'running');
        document.getElementById('currentTestName').textContent = currentTest ? currentTest.name : '测试完成';
    }

    /**
     * 更新进度
     */
    updateProgress() {
        this.updateTestStats();
    }

    /**
     * 重置测试结果
     */
    resetTestResults() {
        this.testResults = [];
        this.testStartTime = Date.now();

        // 清空结果显示
        const resultsContainer = document.getElementById('testResults');
        resultsContainer.innerHTML = `
            <div class="text-center text-slate-500 py-8">
                <i class="fas fa-flask text-4xl mb-4"></i>
                <p>测试运行中...</p>
            </div>
        `;

        // 重置统计
        this.updateTestStats();
    }

    /**
     * 生成测试报告
     */
    generateTestReport() {
        this.testEndTime = Date.now();
        const duration = this.testEndTime - this.testStartTime;

        const totalTests = this.testResults.length;
        const passedTests = this.testResults.filter(r => r.status === 'passed').length;
        const failedTests = this.testResults.filter(r => r.status === 'failed').length;
        const skippedTests = this.testResults.filter(r => r.status === 'skipped').length;

        const successRate = totalTests > 0 ? (passedTests / totalTests * 100).toFixed(1) : 0;

        // 创建测试报告
        const reportElement = document.createElement('div');
        reportElement.className = 'bg-slate-50 rounded-xl p-6 mt-6';
        reportElement.innerHTML = `
            <h3 class="text-xl font-semibold text-slate-800 mb-4">
                <i class="fas fa-chart-line mr-2"></i>测试报告
            </h3>

            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-lg p-4">
                    <div class="text-center">
                        <div class="text-2xl font-bold text-slate-800">${totalTests}</div>
                        <div class="text-sm text-slate-600">总测试数</div>
                    </div>
                </div>
                <div class="bg-green-50 rounded-lg p-4">
                    <div class="text-center">
                        <div class="text-2xl font-bold text-green-800">${passedTests}</div>
                        <div class="text-sm text-green-600">通过</div>
                    </div>
                </div>
                <div class="bg-red-50 rounded-lg p-4">
                    <div class="text-center">
                        <div class="text-2xl font-bold text-red-800">${failedTests}</div>
                        <div class="text-sm text-red-600">失败</div>
                    </div>
                </div>
                <div class="bg-blue-50 rounded-lg p-4">
                    <div class="text-center">
                        <div class="text-2xl font-bold text-blue-800">${successRate}%</div>
                        <div class="text-sm text-blue-600">成功率</div>
                    </div>
                </div>
            </div>

            <div class="mb-4">
                <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-medium text-slate-600">测试用时</span>
                    <span class="text-sm text-slate-500">${(duration / 1000).toFixed(2)}秒</span>
                </div>
                <div class="flex items-center justify-between">
                    <span class="text-sm font-medium text-slate-600">测试时间</span>
                    <span class="text-sm text-slate-500">${new Date(this.testStartTime).toLocaleString()}</span>
                </div>
            </div>

            <div class="mb-4">
                <h4 class="font-semibold text-slate-800 mb-2">测试建议</h4>
                <div class="space-y-2">
                    ${this.generateTestRecommendations()}
                </div>
            </div>

            <div class="flex space-x-4">
                <button id="exportTestReport" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    <i class="fas fa-download mr-2"></i>导出报告
                </button>
                <button id="rerunFailedTests" class="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">
                    <i class="fas fa-redo mr-2"></i>重新运行失败测试
                </button>
            </div>
        `;

        document.getElementById('testResults').appendChild(reportElement);

        // 绑定导出按钮事件
        document.getElementById('exportTestReport').addEventListener('click', () => {
            this.exportTestReport();
        });

        // 绑定重新运行按钮事件
        document.getElementById('rerunFailedTests').addEventListener('click', () => {
            this.rerunFailedTests();
        });

        console.log('📊 测试报告生成完成');
        console.log(`✅ 通过: ${passedTests}, ❌ 失败: ${failedTests}, ⏭️ 跳过: ${skippedTests}`);
        console.log(`📈 成功率: ${successRate}%, 用时: ${(duration / 1000).toFixed(2)}秒`);
    }

    /**
     * 生成测试建议
     */
    generateTestRecommendations() {
        const recommendations = [];

        const failedTests = this.testResults.filter(r => r.status === 'failed');
        if (failedTests.length > 0) {
            recommendations.push(`<div class="flex items-start space-x-2">
                <i class="fas fa-exclamation-triangle text-yellow-600 mt-1"></i>
                <div>
                    <p class="font-medium text-yellow-800">修复失败测试</p>
                    <p class="text-sm text-yellow-700">有${failedTests.length}个测试失败，建议优先修复这些问题</p>
                </div>
            </div>`);
        }

        const successRate = (this.testResults.filter(r => r.status === 'passed').length / this.testResults.length * 100);
        if (successRate < 90) {
            recommendations.push(`<div class="flex items-start space-x-2">
                <i class="fas fa-chart-line text-blue-600 mt-1"></i>
                <div>
                    <p class="font-medium text-blue-800">提高测试覆盖率</p>
                    <p class="text-sm text-blue-700">当前成功率${successRate.toFixed(1)}%，建议提高测试覆盖率</p>
                </div>
            </div>`);
        }

        recommendations.push(`<div class="flex items-start space-x-2">
            <i class="fas fa-rocket text-green-600 mt-1"></i>
            <div>
                <p class="font-medium text-green-800">性能优化</p>
                <p class="text-sm text-green-700">定期进行性能测试，确保用户体验</p>
            </div>
        </div>`);

        return recommendations.join('');
    }

    /**
     * 导出测试报告
     */
    exportTestReport() {
        const report = {
            title: '分析结果页面测试报告',
            timestamp: new Date().toISOString(),
            duration: this.testEndTime - this.testStartTime,
            summary: {
                total: this.testResults.length,
                passed: this.testResults.filter(r => r.status === 'passed').length,
                failed: this.testResults.filter(r => r.status === 'failed').length,
                skipped: this.testResults.filter(r => r.status === 'skipped').length,
                successRate: (this.testResults.filter(r => r.status === 'passed').length / this.testResults.length * 100).toFixed(1)
            },
            results: this.testResults,
            environment: {
                userAgent: navigator.userAgent,
                viewport: `${window.innerWidth}x${window.innerHeight}`,
                timestamp: new Date().toISOString()
            }
        };

        const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `analysis-results-test-report-${new Date().toISOString().split('T')[0]}.json`;
        a.click();
        URL.revokeObjectURL(url);

        console.log('📄 测试报告已导出');
    }

    /**
     * 重新运行失败测试
     */
    rerunFailedTests() {
        const failedTests = this.testResults.filter(r => r.status === 'failed');
        if (failedTests.length === 0) {
            alert('没有失败的测试需要重新运行');
            return;
        }

        console.log(`🔄 重新运行${failedTests.length}个失败的测试...`);
        this.runAllTests();
    }

    /**
     * 检查页面元素
     */
    checkPageElements() {
        // 可以在这里添加页面元素变化的监听逻辑
    }

    /**
     * 延迟函数
     */
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 全局测试套件实例
let testSuite;

// 启动测试套件的函数
function startAnalysisResultsTest() {
    console.log('🧪 启动分析结果页面测试套件...');
    testSuite = new AnalysisResultsTestSuite();
}

// 在页面加载完成后，自动检查是否需要启动测试
document.addEventListener('DOMContentLoaded', () => {
    // 检查URL参数是否包含测试标志
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('test') || urlParams.has('debug')) {
        setTimeout(() => {
            startAnalysisResultsTest();
        }, 2000);
    }
});

// 导出到全局作用域
window.startAnalysisResultsTest = startAnalysisResultsTest;

// 添加调试信息
console.log('🧪 分析结果页面测试脚本已加载');
console.log('💡 使用 startAnalysisResultsTest() 启动测试');
console.log('🔗 或在URL中添加 ?test 参数自动启动测试');